package com.sunwhite.herostore.cmdhandler;

import com.sunwhite.herostore.common.UserManager;
import com.sunwhite.herostore.entity.User;
import com.sunwhite.herostore.entity.UserEntity;
import com.sunwhite.herostore.msg.GameMsgProtocol;
import com.sunwhite.herostore.service.LoginService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户登录消息的处理器
 */
public class UserLoginCmdHandle implements CmdHandler<GameMsgProtocol.UserLoginCmd> {
    /*
    日志对象
     */
    private final static Logger log= LoggerFactory.getLogger(UserLoginCmdHandle.class);

    /**
     * 用户登陆状态字典, 防止用户连点登陆按钮
     */
    static private final Map<String, Long> USER_LOGIN_STATE_MAP = new ConcurrentHashMap<>();

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd msg) {
        if (null==ctx||null==msg){
            return;
        }
        log.info("用户登录消息处理器，当前线程:{}",Thread.currentThread().getName());
        String userName = msg.getUserName();
        String password = msg.getPassword();
        //获取userService
        //判断用户是否登录成功
        LoginService.getInstance().login(userName,password,(userEntity)->{
           //移除用户状态

            if (null == userEntity) {
                log.error("用户登陆失败, userName = {}", msg.getUserName());
                return null;
            }

            log.info(
                    "用户登陆成功, userId = {}, userName = {}",
                    userEntity.userId,
                    userEntity.userName
            );
            //新建用户
            User user = new User();
            user.userId=userEntity.userId;
            user.userName=userEntity.userName;
            user.heroAvatar=userEntity.heroAvatar;
            //将用户加入用户管理器
            UserManager.addUser(user);

            //将用户ID附着到channel上
            ctx.channel().attr(AttributeKey.valueOf("userId")).set(user.userId);

            //登录结构构建者
            GameMsgProtocol.UserLoginResult.Builder userLoginResultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
            userLoginResultBuilder.setUserId(user.userId);
            userLoginResultBuilder.setUserName(user.userName);
            userLoginResultBuilder.setHeroAvatar(user.heroAvatar);
            GameMsgProtocol.UserLoginResult userLoginResult = userLoginResultBuilder.build();
            ctx.writeAndFlush(userLoginResult);
            return null;
        });



    }
}
